<?php

namespace app\index\controller;

use think\exception\ValidateException;
use app\model\Technical;
use app\model\Config;
use app\model\Category;
use app\model\TechnicalCategory;
use app\model\TechnicalLevel;
use app\model\Comment;
use app\model\Goods;
use app\model\Member;
use app\model\Store;
use think\facade\Db;

class TechnicalController extends Base
{

    public function list()
    {
        $cid = input('post.cid');
        $keyword = input('post.keyword');

        $config = Config::getconfig();
        $longitude = input('post.longitude'); //经度信息
        $latitude = input('post.latitude'); //纬度信息
        // if (!empty($longitude) && !empty($latitude)) {
        //     $sql = "select * from (select id,weid,sort,cate_ids,title,region_name,touxiang,status, ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($latitude*PI()/180-`latitude`*PI()/180)/2),2)+COS($latitude*PI()/180)*COS(`latitude`*PI()/180)*POW(SIN(($longitude*PI()/180-`longitude`*PI()/180)/2),2)))*1000) AS distance from " . (new Technical)->getTable() . " order by distance ) as a where a.distance<=".($config['technicaldistance']*1000)." and status=1 ";
        // } else {
        //     $sql = "select * from " . (new Technical)->getTable() . " where status=1 ";
        // }

        $sql = "select * from " . (new Technical)->getTable() . " where status=1 ";

        $sql .=  " and `weid` = " . weid();
        if (trim($keyword)) {
            $sql .=  " and `title` LIKE '%" . $keyword . "%'";
        }

        if ($cid) {
            $sql .=  " and FIND_IN_SET('" . $cid . "',cate_ids) ";
        }

        $sql .=  " order by sort asc,id desc";

        $data = Db::query($sql);

        foreach ($data as &$vo) {
            $vo['touxiang'] = toimg($vo['touxiang']);
            $vo['distance'] = round(($vo['distance']) / 1000, 1);
        }
        $res['data'] = $data;
        return $this->json(['data' => $res]);
    }

    public function detail($id)
    {
        $data = Technical::find($id);

        if (!empty($data)) {
            $data = $data->toArray();
            $data['category_name'] = TechnicalCategory::getTitle($data['category_id']);
            $data['level_name'] = TechnicalLevel::getTitle($data['level']);
            $data['pid_name'] = Member::getpidname($data['uid']);
            $data['comment'] = Comment::total_byuid($data['uid']);
            $data['create_time'] = time_ymd($data['create_time']);

            if(empty($data['sid'])){
                $data['store'] = '平台师傅';
            }else{
                $data['store'] = Store::getTitle($data['sid']);
            }

            $data['goodslist'] = Goods::where(['weid' => weid(), 'ptype' => 2])->whereIn('cat_id', $data['cate_ids'])->select()->toArray();
            $data['goodslist'] = Goods::setGoodslist($data['goodslist']);
        }

        return $this->json(['data' => $data]);
    }
}
